package com.shao.im.webSocket.handler;

import com.alibaba.fastjson2.JSON;
import com.shao.im.entity.Message;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * 文本帧的消息处理器
 */
@Slf4j
public class TextMessageChannelHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.debug("[WebSocket Conn] 有一个客户端连接了服务器... - {} ", ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.debug("[WebSocket DisConn] 有一个客户端断开了连接... - {}", ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        // 读取客户端传过来的json字符串，并转换成实体对象
        Message message = JSON.parseObject(msg.text(), Message.class);
        log.debug("[webSocket message] 接收到了客户端的消息 - {} -{}", message, ctx.channel());
        ctx.fireChannelRead(message);
    }
}
